package com.smartao.base.department;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smartao.base.Constant;
import com.smartao.base.init.InitializeServiceOrder;
import com.smartao.base.selectitem.Selectitem;
import com.smartao.base.selectitem.SelectitemService;
import com.smartao.core.init.AbstractDataInitializeService;

@Service
public class DepartmentInitializeService extends AbstractDataInitializeService{
	@Autowired
	private DepartmentService departmentService;
	@Autowired
	private SelectitemService selectitemService;

	@Override
	public int getOrder() {
		return InitializeServiceOrder.INIT_ORDER_DEPARTMENT;
	}

	@Override
	public void initData() throws Exception {
		Department dept = departmentService.findRoot();
		if(dept!=null){
			return;
		}

		Selectitem tradeUnionDimension = selectitemService.findByCode("SELECTITEM_DEPARTMENT_DIMENTION_TRADEUNION");
		Department tradeUnion = new Department();
		tradeUnion.setDimension(tradeUnionDimension);
		tradeUnion.setName("总工会");
		departmentService.save(tradeUnion);
		
		Selectitem adminDimension = selectitemService.findByCode(Constant.SELECTITEM_DEPARTMENT_DIMENTION_ADMIN);
		Department root = new Department();
		root.setDimension(adminDimension);
		root.setName("总公司");
		departmentService.save(root);
		
		Department d1 = new Department();
		d1.setParent(root);
		d1.setName("开发部");
		d1.setDimension(adminDimension);
		departmentService.save(d1);
		
		// parent需要手动重新加载一次；否则新添加的Department有leftKey，rightKey不一致；
		root = departmentService.findOne(root.getId());
		
		Department d2 = new Department();
		d2.setParent(root);
		d2.setName("销售部");
		d2.setDimension(adminDimension);
		departmentService.save(d2);
		
		d1 = departmentService.findOne(d1.getId());
		Department d3 = new Department();
		d3.setParent(d1);
		d3.setName("产品研发部");
		d3.setDimension(adminDimension);
		departmentService.save(d3);
		
		d1 = departmentService.findOne(d1.getId());
		Department d4 = new Department();
		d4.setParent(d1);
		d4.setName("项目开发部");
		d4.setDimension(adminDimension);
		departmentService.save(d4);
		
	}
}
